package com.kirito.mvcframework.v1;

import com.kirito.mvcframework.Annotation.Autowired;
import com.kirito.mvcframework.Annotation.Controller;
import com.kirito.mvcframework.Annotation.RequestMapping;
import com.kirito.mvcframework.Annotation.Service;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @ClassName DispatcherServlet
 * @Description: TODO
 * @Author kirito
 * @Date 2021/1/7
 * @Version V1.0
 **/
public class DispatcherServlet extends HttpServlet {
    private Map<String,Object> mapping  = new HashMap<String, Object>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    protected void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String url = req.getRequestURI();

        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replace("/+", "/");
        if (!this.mapping.containsKey(url)){
            resp.getWriter().write("404 not found");
            return;
        }
        Method method = (Method) this.mapping.get(url);
        Map<String,String[]> prams = req.getParameterMap();

        method.invoke(this.mapping.get(method.getDeclaringClass().getName()),new Object[]{req,resp,prams.get("name")[0]});
    }
    //init方法肯定干得的初始化的工作
    //inti首先我得初始化所有的相关的类，IOC容器、servletBean
    @Override
    public void init(ServletConfig config) throws ServletException {
        InputStream is = null;
        try {
            Properties properties = new Properties();
            is = this.getClass().getClassLoader().getResourceAsStream(config.getInitParameter("contextConfigLocation"));
            properties.load(is);
            String scanPackage = properties.getProperty("scanPackage");

            doScanner(scanPackage);
            for (String clazzName : this.mapping.keySet()){
                if (clazzName.contains(".")){
                    Class<?> clazz = Class.forName(clazzName);
                    if (clazz.isAnnotationPresent(Controller.class)) {
                        this.mapping.put(clazzName,clazz.newInstance());
                        String baseUrl = "";
                        if (clazz.isAnnotationPresent(RequestMapping.class)){
                            RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
                            baseUrl = requestMapping.value();
                        }
                        Method[] methods = clazz.getMethods();
                        for (Method method : methods) {
                            if (method.isAnnotationPresent(RequestMapping.class)){
                                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                                String url = (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                                this.mapping.put(url,method);
                                System.out.println("Mapped " + url + "," + method);
                            }
                        }

                    }else if (clazz.isAnnotationPresent(Service.class)){
                        Service annotation = clazz.getAnnotation(Service.class);
                        String beanName = annotation.value();
                        if ("".equals(beanName)){
                            beanName = clazz.getName();
                        }
                        Object instance = clazz.newInstance();
                        this.mapping.put(beanName,instance);
                        for (Class<?> i : clazz.getInterfaces()){
                            this.mapping.put(i.getName(),instance);
                        }
                    }else{
                        continue;
                    }
                    for (Object object : this.mapping.values()){
                        if (object == null){
                            continue;
                        }
                        Class claxx = object.getClass();
                        if (claxx.isAnnotationPresent(Controller.class)){
                            Field[] fields = claxx.getFields();
                            for (Field field : fields){
                                if (!field.isAnnotationPresent(Autowired.class)){
                                    continue;
                                }
                                Autowired autowired = field.getAnnotation(Autowired.class);
                                String baseName = autowired.value();
                                if ("".equals(baseName)){
                                    baseName = field.getType().getName();
                                }
                                field.setAccessible(true);
                                try {
                                    field.set(this.mapping.get(claxx.getName()),this.mapping.get(baseName));
                                }catch (Exception e){
                                    e.printStackTrace();
                                }finally {
                                    if (is != null){
                                        try {
                                            is.close();
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }
                                    }
                                }
                                System.out.print("kirito MVC Framework is init");
                            }
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classDir = new File(url.getFile());
        for (File file : classDir.listFiles()){
            if (file.isDirectory()){
                doScanner(scanPackage+"."+file.getName());
            }else{
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                String clazzName = (scanPackage+"."+file.getName().replace(".class",""));
                mapping.put(clazzName,null);
            }

        }
    }
}
